import os

path = os.path
from importlib import import_module, util
from datetime import datetime
import tarfile
import requests
import time
from RPA.Browser.Playwright import Playwright
import ddddocr
import cv2
import numpy as np
from PIL import Image

# 创建DdddOcr实例
ocr = ddddocr.DdddOcr(show_ad=False)

sn = import_module("switch_network")
printer = import_module("printer").IndentPrinter(indent=1)
auth_info = None
data_path = os.environ["DATA_PATH"]

session = requests.Session()
browser = Playwright()
browser.new_browser(headless=False)
browser.new_context(ignoreHTTPSErrors=True)
browser.new_page(url="about:blank")
now = datetime.now()

USERNAME = "18819622357"
PASSWORD = "Gmcc202505*"

def get_ima_code(path):
    # 读取图像
    image = cv2.imread(path)

    # 将图像从BGR转换为HSV
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

    # 定义红色的HSV范围
    lower_red_1 = np.array([0, 100, 100])
    upper_red_1 = np.array([10, 255, 255])
    lower_red_2 = np.array([160, 100, 100])
    upper_red_2 = np.array([180, 255, 255])

    # 创建掩膜
    mask1 = cv2.inRange(hsv, lower_red_1, upper_red_1)
    mask2 = cv2.inRange(hsv, lower_red_2, upper_red_2)

    # 合并两个掩膜
    mask = mask1 + mask2

    kernel = np.ones((3, 3), np.uint8)
    # 对掩膜进行膨胀操作，以连接邻近的红色区域
    mask = cv2.dilate(mask, kernel, iterations=1)
    # 应用掩膜到原始图像
    red_only = cv2.bitwise_and(image, image, mask=mask)
    # 创建白色背景图像，大小与原图相同
    white_background = np.ones_like(image) * 255

    # 使用掩膜将红色部分叠加到白色背景上
    # 首先反转掩膜，使得非红色区域变为白色
    inverse_mask = cv2.bitwise_not(mask)
    # 将白色背景应用到非红色区域
    white_background_with_holes = cv2.bitwise_and(
        white_background, white_background, mask=inverse_mask
    )
    # 将红色部分和白色背景合并
    result = cv2.add(red_only, white_background_with_holes)

    # 显示结果或保存结果
    # cv2.imshow("Red on White Background", result)
    cv2.imwrite(f"{path}.jpg", result)

    with open(f"{path}.jpg", "rb") as f:
        img_bytes = f.read()

    # 使用classification方法进行预测
    code = ocr.classification(img_bytes)
    return code


def main():
    now_str = now.strftime("%Y%m%d")
    local_tar_path = path.join(data_path, f"软探针数据{now_str}.tar.gz")
    
    if sn.wait_for_system("10.243.24.46", "11277"):
        printer("软探针系统已可用")
        browser.go_to("https://10.243.24.46:11277/manage/rtz-web/login")
        browser.wait_for_elements_state('[name="loginName"]')
        time.sleep(2)
        browser.type_text(selector='[name="loginName"]', txt=USERNAME)
        browser.type_text(selector='[name="password"]', txt=PASSWORD)
        # 获取验证码图片
        captcha_img_selector = ".captchaCode_box img"
        captcha_path = browser.take_screenshot(
            filename=path.join(os.getcwd(), "captcha"), selector=captcha_img_selector
        )
        result = get_ima_code(captcha_path)
        printer(f"图片验证码识别结果: {result}")
        # 在 placeholder="验证码" 的输入框中输入验证码
        browser.type_text(selector='input[placeholder="验证码"]', txt=result)
        time.sleep(60)
        browser.click(selector=".el-form-item__content>.el-button")
        browser.wait_for_elements_state(".sidebar")

        printer("登录软探针检测平台成功")
        cookies = browser.get_cookies()
        cookies_dict = {}
        for item in cookies:
            cookies_dict[item["name"]] = item["value"]

        printer(cookies_dict)
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36"
        }

        printer("开始下载文件")

        res = requests.get(
            f"https://10.243.24.46:11277/manage/dataOsgi/{now_str}.tar.gz",
            verify=False,
            headers=headers,
            stream=True,
            cookies=cookies_dict,
        )
        if res.status_code == 200:
            if os.path.exists(local_tar_path):
                printer(
                    f"[下载文件] {now_str} TAR 文件已存在，删除旧文件：{local_tar_path}"
                )
                os.remove(local_tar_path)
            total_length = int(res.headers.get("content-length"))
            with open(local_tar_path, "wb") as file:

                downloaded = 0
                for chunk in res.iter_content(chunk_size=8192):
                    downloaded += len(chunk)
                    file.write(chunk)
                    done = int(50 * downloaded / total_length)  # 计算进度条长度
                    percentage = (downloaded / total_length) * 100
                    print(
                        f"\r[下载进度]: [{'=' * done}{' ' * (50-done)}] {percentage:.2f}%",
                        end="",
                        flush=True,
                    )
            printer("")
            printer(f"[下载文件]  {now_str} 下载完成，文件已保存到：{local_tar_path}")
            printer("开始解压文件")
            try:
                target_path = f"data/hy/pon/{now_str}/0668_{now_str}.csv"
                with tarfile.open(local_tar_path, "r:gz") as tar:
                    # 检查文件是否存在于ZIP文件中
                    members = tar.getnames()
                    print(members)
                    if target_path in members:

                        # 计算输出文件的完整路径
                        output_file_path = os.path.join(
                            data_path, f"0668_{now_str}.csv"
                        )
                        # 解压指定文件
                        tar_member = tar.getmember(target_path)
                        tar.extract(member=tar_member, path=output_file_path)
                        print(f"文件已成功解压到：{output_file_path}")
                    else:
                        err_msg = f"在软探针压缩文件中未找到指定的文件：{target_path}"
                        raise ValueError(err_msg)
            except Exception as e:
                printer("[解压软探针文件] 失败，发生错误：", e)
                raise e
            else:
                printer("下载文件失败")
